<template>
    <el-tooltip v-if="trDisabled && (form && form.orderStatus === '1')" :visible="!props.applyIsDisabled" class="box-item"
                content="请先点击（处方新增）按钮后，再添加药品"
                effect="dark" placement="right">
        <el-button :disabled="!props.applyIsDisabled" plain type="primary" @click="handleAddDrug">
            <template #icon>
                <i-ep-plus/>
            </template>
            添加药品
        </el-button>
    </el-tooltip>
    <el-button v-if="trDisabled  && (form && form.orderStatus === '1')" :disabled="!props.applyIsDisabled" plain type="danger"
               @click="emptyDrugList(true)">
        <template #icon>
            <i-ep-delete-filled/>
        </template>
        清空
    </el-button>
    <div style="height: calc(100% - 20px);overflow-y: auto;">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-row :gutter="10" class="mt5 top-row">
                <el-form-item class="mr20" label="是否代煎" prop="isDecoction" style="margin-left: 20px">
                    <el-select v-model="form.isDecoction" :disabled="!trDisabled" class="width-120"
                               placeholder="请选择">
                        <el-option v-for="dict in decoctionDict" :key="dict.dictValue" :label="dict.dictLabel"
                                   :value="dict.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="mr20" label="途径" prop="channel">
                    <administration-index :clearable="false" :disabled="!trDisabled"
                                          :placeholder="'请选择途径'" :value="form.channel" class="width-120"
                                          @administrationInfoChange="administrationInfoChange($event)"/>
                </el-form-item>
                <el-form-item class="mr20" label="频次" prop="performFreq">
                    <perform-index ref="performIndex" :clearable="false" :disabled="!trDisabled"
                                   :placeholder="'请选择频次'"
                                   :value="form.performFreq" class="width-120"
                                   @performFreqInfoChange="performFreqInfoChange($event)"/>
                </el-form-item>
                <el-form-item class="mr20" label="剂数" prop="repetition">
                    <el-input v-model="form.repetition" :disabled="!trDisabled" clearable style="width: 60px"
                              @blur="repetitionBlur"/>
                </el-form-item>
                <el-form-item class="mr20" label="">
                    共计：<span class="mr5" style="color:#ff0000;">{{ itemCount }}</span>味药材，
                    总计：<span class="mr5" style="color:#ff0000;">{{ sumMoney }} </span>元
                </el-form-item>
            </el-row>
            <el-row :gutter="10" style="padding-top: 30px;margin-right: 0">
                <el-col v-for="(item, index) in form.chinesePrescriptionItemList" :key="index"
                        class="div-style west-style" style="max-width: 15.5%;border-radius: 10px;">
                    <div style="margin-bottom: -10px;">{{ index + 1 }}
                        <el-tag v-if="trDisabled" key="1" effect="dark" round
                                style="float: right;cursor: pointer;"
                                type="danger" @click="removeDiv(index)">
                            X
                        </el-tag>
                        <div v-else>&nbsp;</div>
                        <div class="west-style" style="margin-top: 5px">
                            <el-row :gutter="0">
                                <el-col :span="14">
                                    <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.drugName'"
                                                  :rules="rules.drugName" class="table-form-margin">
                                        <el-popover :offset="0" :visible="visibleOpen[index]" placement="bottom"
                                                    popper-class="remove-popover" trigger="click" width="1190">
                                            <template #reference>
                                                <el-input ref="inputRef" v-model="item.drugName" :disabled="!trDisabled"
                                                          :tabindex="index" placeholder="请输入需要检索的数据"
                                                          @blur="itemNameBlur(index)"
                                                          @focus="itemNameInput($event, index, item)"
                                                          @input="itemNameInput($event, index, item)"
                                                          @keydown="onKeyDown($event,index, item)"/>
                                            </template>
                                            <el-table :border="true" ref="tabzyRef" :data="tableBodyList" height="200px"
                                                      highlight-current-row stripe
                                                      @row-click="rowClick($event, index, item)"
                                                      @current-change="handleCurrentChange(item,index)">
                                                <el-table-column v-for="(item, index) in tableHeadList" :key="index"
                                                                 :align="item.align ? item.align : 'center'"
                                                                 :label="item.label"
                                                                 :property="item.prop" :show-overflow-tooltip="true"
                                                                 :width="item.width ? item.width : '90'">
                                                    <template #default="scope">
                                                    <span v-if="item.class === 'dict'">
                                                        <dict-data-tag :options="dictDataMap[item.dictType]"
                                                                       :value="scope.row[item.prop]"/>
                                                    </span>
                                                        <span v-else-if="item.class === 'date'">
                                                        <span>{{
                                                                $parseTime(scope.row[item.prop], '{y}-{m}-{d}')
                                                            }}</span>
                                                    </span>
                                                        <span v-else-if="item.class === 'time'">
                                                        <span>{{
                                                                $parseTime(scope.row[item.prop], '{y}-{m}-{d} {h}:{i}:{s}')
                                                            }}</span>
                                                    </span>
                                                        <span v-else>
                                                        <span>{{ scope.row[item.prop] }}</span>
                                                    </span>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                            <el-button style="float: right;margin-top: 5px"
                                                       @click="closePopover(index)">
                                                关闭
                                            </el-button>
                                        </el-popover>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.num'"
                                                  :rules="rules.num"
                                                  class="table-form-margin">
                                        <el-input v-model="item.num" :class="'num-class' + index"
                                                  :disabled="!trDisabled" :tabindex="index + '-' + 1" clearable
                                                  placeholder="数量"
                                                  @blur="numBlur(index, item)">
                                            <template #append>
                                                {{ item.unitName}}
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="0">
                                <el-col :span="14">
                                    <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.remarks'"
                                                  class="table-form-margin">
                                        <el-input v-model="item.remarks" :disabled="!trDisabled" clearable
                                                  placeholder="备注"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.sumPrice'"
                                                  :rules="rules.sumPrice" class="table-form-margin">
                                        <el-input v-model="item.sumPrice" disabled>
                                            <template #append>
                                                元
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </div>


                </el-col>
            </el-row>
        </el-form>
    </div>
</template>


<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {jsonStrInObj, prescriptionList} from "@/utils/autoComplete.ts";
import {positiveNumberNotNull} from "@/utils/myRules.ts";
import {listSysOrgDict} from "@/api/system/sysOrgDict.ts";
import {autoPrescriptionList} from "@/api/drug/drugStock.ts"
import {addPrescriptionApply} from "@/api/patient/prescriptionApply.ts";
import {listPrescriptionItem} from "@/api/patient/prescriptionItem.ts";

const emits = defineEmits(["itemSubmitOk", "submitOk"])
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const drugName = ref("")
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no', 'dose_unit', 'sys_drop_speed'))
// 药品总数量
const itemCount = ref(0)
// 药品总金额
const sumMoney = ref(0.00)
// ref数组

//自动补全表格
const tabzyRef = ref();
// 当前选中的行索引
const currentRowIndex = ref(-1);

//是否代煎字典
const decoctionDict = ref<any>([])
const form = ref<any>({
    isDecoction: '1',
    channel: '89',
    // 默认 一日两次
    performFreq: '978D4D8D3ACE4221B3368CD5186E1351',
    repetition: 1,
    // 药品价格list
    chinesePrescriptionItemList: []
})
const visibleOpen = ref([false,])
const formRef = ref()
const rules = ref<any>({
    drugName: [
        {required: true, message: "不能为空", trigger: "blur"}
    ],
    isDecoction: [
        {required: true, message: "代煎不能为空", trigger: "change"}
    ],
    channel: [
        {required: true, message: "用药途径不能为空", trigger: "change"}
    ],
    performFreq: [
        {required: true, message: "频次不能为空", trigger: "change"}
    ],
    num: [
        {required: true, validator: positiveNumberNotNull, trigger: "blur"}
    ],
    repetition: [
        {required: true, validator: positiveNumberNotNull, trigger: "blur"}
    ],
})
const props = defineProps({
    orgId: {
        type: String,
        default: ""
    },
    applyIsDisabled: {
        type: Boolean,
        default: true
    },
});
// 处方主信息是否禁用
const isDisabled = ref<boolean>(true)


// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(prescriptionList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

const trDisabled = ref<boolean>(false)

const autoForm = ref<any>({
    drugClassArray: "",
    storageId: "",
    itemInfo: "",
    orgId: props.orgId,
    isMinPackSize: "1"
})

/**
 * 数量input焦点消失事件
 * @param e
 * @param index
 * @param item
 */
function numBlur(_index: number, item: any) {
    item.sumPrice = Number((item.price * item.num).toFixed(4))
    sunUp()
}

/** 计算总金额 */
function sunUp() {
    sumMoney.value = 0.00
    itemCount.value = 0
    let sumMoneyThis = 0.00
    form.value.chinesePrescriptionItemList.forEach((item: any) => {
        sumMoneyThis += Number(item.sumPrice)
    })
    sumMoney.value = Number((sumMoneyThis * form.value.repetition).toFixed(4))
    itemCount.value = form.value.chinesePrescriptionItemList.length
}

/** 剂数焦点消失事件 */
function repetitionBlur() {
    sunUp()
}

function itemNameBlur(index: number) {
    closePopover(index)
    currentRowIndex.value = -1;
}

function administrationInfoChange(e: any) {
    const dict = toRaw(e)
    form.value.channel = dict.dictValue
}

/**
 * 频次点击事件
 */
function performFreqInfoChange(e: any) {
    const performFreqInfo = toRaw(e)
    form.value.performFreq = performFreqInfo.freqId
    form.value.performFreqInfo = performFreqInfo
}

/**
 * 打开中药明细事件
 * @param drugClassArrayParam
 * @param storageId
 */
function setDrugClassArray(drugClassArrayParam: any, storageId: string) {
    listSysOrgDictFun()
    autoForm.value.drugClassArray = drugClassArrayParam
    autoForm.value.storageId = storageId
    trDisabled.value = true
}

function closePopover(index: number) {
    visibleOpen.value[index] = false
    // input焦点跳转到num上
    nextTick(() => {
        const nextIndex = index + '-1';
        const nextElement = document.querySelector(`[tabindex="${nextIndex}"]`);
        if (nextElement) {
            //@ts-ignore
            nextElement.focus();
        }
    });
}


/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
    row.sumPrice = 0.00
    row.singleDosageMin = e.dose
    row.singleDosage = e.dose
    row.singleUnitName = e.doseUnitsName
    row.singleUnit = e.doseUnits
    row.unitName = e.unitsName
    row.minUnits = e.minUnits
    row.packageUnits = e.packageUnits
    row.packageSpec = e.packageSpec
    row.minSpec = e.minSpec
    row.packSize = e.packSize
    row.firmName = e.firmName
    row.firmId = e.firmId
    row.drugName = e.drugName
    row.drugCode = e.drugCode
    row.price = e.price
    row.abidance = 1
    row.sumPrice = e.price * 1
    row.batchNo = e.batchNo
    row.packageNum = e.packageNum
    row.stockId = e.stockId
    row.tradePrice = e.tradePrice
    row.priceId = e.drugPriceId
    row.channel = e.channel
    row.performFreq = e.performFreq
    row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
    row.drugInfoId = e.drugInfoId
    row.identicalInfoId = e.identicalInfoId
    row.sort = index + 1
    tableBodyList.value = []
    closePopover(index)
}

/** 项目名称自动补全检索 */
function itemNameInput(drugName: String, index: number, item: any) {
    if (typeof drugName == "string") {
        autoForm.value.itemInfo = drugName
    } else {
        autoForm.value.itemInfo = item.drugName
    }
    getListDrugItem(index)
}

/** 自动补全后台查询 */
function getListDrugItem(index: number) {
    if (autoForm.value.itemInfo) {
        autoForm.value.orgId = props.orgId
        // 打开自动补全弹出框
        visibleOpen.value[index] = true
        autoPrescriptionList(autoForm.value).then(res => {
            tableBodyList.value = res.data
        })
    } else {
        tableBodyList.value = []
    }
}

/** 添加药品 */
function handleAddDrug() {
    (formRef.value as any).validate((valid) => {
        if (valid) {
            form.value.chinesePrescriptionItemList.push({
                // 是否免皮试 保存、修改时需要单独处理 true-> Y , false-> N
                noSkin: "Y",
                sumPrice: 0.00,
                price: 0.00,
                drugName: "",
                abidance: 1,
                num: 1
            })
            trDisabled.value = true
            visibleOpen.value.push(false)
            form.value.orderStatus = '1'
        }
    })
}

function emptyDrugList(type) {
    if (type) {
        ElMessageBox.confirm('重置后未保存的数据将会丢失，确定要继续操作吗？',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            form.value.chinesePrescriptionItemList = []

        }).catch(() => {
            ElMessage.info("操作终止")
        })
    } else {
        form.value.chinesePrescriptionItemList = []
    }
    itemCount.value = 0
    sumMoney.value = 0.00
    form.value.repetition = 1
}

function listSysOrgDictFun() {
    const param = {
        dictType: "clinic_dict",
        delFlag: "0",
        orgId: props.orgId
    }
    listSysOrgDict(param).then((res: resType) => {
        decoctionDict.value = res.data
    })
}

/**
 * 删除单个中药div
 * @param index
 */
function removeDiv(index: number) {
    ElMessageBox.confirm('确定要删除吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        form.value.chinesePrescriptionItemList.splice(index, 1)
        sunUp()
    }).catch(() => {
        ElMessage.info("操作终止")
    })
}

/**
 * 明细行数据校验
 */
function itemValidate() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            emits("itemSubmitOk", form.value)
        }
    })
}

function saveIsOk(prescriptionFormParam: any) {
    ElMessageBox.confirm('确定要进行处方保存操作吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 不代煎
        prescriptionFormParam.isDecoction = form.value.isDecoction
        prescriptionFormParam.repetition = form.value.repetition
        prescriptionFormParam.isUpdateDoctorId = "Y"
        form.value.chinesePrescriptionItemList.forEach((item: any) => {
            item.channel = form.value.channel
            item.performFreq = form.value.performFreq
        })
        prescriptionFormParam.prescriptionItemBoList = form.value.chinesePrescriptionItemList
        addPrescriptionApply(prescriptionFormParam).then(() => {
            emits("submitOk")
            itemCount.value = 0
            sumMoney.value = 0.00
            form.value.repetition = 1
            ElMessage.success("处方保存成功")
        })
    }).catch(() => {
        ElMessage.info("操作终止")
    })
}

function applyRowClick(row: any) {
    const rows = toRaw(row)
    form.value.isDecoction = rows.isDecoction
    form.value.repetition = rows.repetition
    form.value.chinesePrescriptionItemList = []
    form.value.orderStatus = rows.orderStatus
    listPrescriptionItem({applyId: rows.applyId, orgId: props.orgId}).then((res: any) => {
        trDisabled.value = form.value.orderStatus === '1';
        res.data.forEach((item: any) => {
            item.itemId = ""
            form.value.chinesePrescriptionItemList.push(item)
            form.value.channel = item.channel
            form.value.performFreq = item.performFreq
            const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
            item.unitName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
        })
        sunUp()
    })
}

/*********************************************  模板数据引用  *********************************************/
function templateQuote(list: any) {
    form.value.isDecoction = list[0].isDecoction
    form.value.repetition = list[0].repetition
    form.value.channel = list[0].channel
    form.value.performFreq = list[0].performFreq
    list.forEach((item: any) => {
        item.drugName = item.drugName || item.itemName
        item.drugCode = item.drugCode || item.itemCode
    })
    form.value.chinesePrescriptionItemList = list
    sunUp()
}

// 处理键盘事件
function onKeyDown(event: KeyboardEvent,index:number,item) {

//console.log(currentRowIndex.value);
if (event.key === 'ArrowDown') {
  event.preventDefault();
  if (currentRowIndex.value < tableBodyList.value.length - 1) {
    currentRowIndex.value++;
  }
  //console.log(tabzyRef.value[index])
  tabzyRef.value[index].setCurrentRow(tableBodyList.value[currentRowIndex.value])
} else if (event.key === 'ArrowUp') {
  event.preventDefault();
  if (currentRowIndex.value > 0) {
    currentRowIndex.value--;
  }
  tabzyRef.value[index].setCurrentRow(tableBodyList.value[currentRowIndex.value])
} else if (event.key === 'Enter') {
  event.preventDefault();
  if (currentRowIndex.value !== -1) {
    rowClick(tableBodyList.value[currentRowIndex.value], index , item);
  }
}
}

//当前选中数据
const currentRow = ref(null);
//选中行事件
function handleCurrentChange(val,index) {
currentRow.value = val;
//console.log(currentRow.value)
if (currentRow.value) {
  scrollToCurrentRow(index);
}
}
//设置滚动条
function scrollToCurrentRow(index){
if (!currentRow.value || !tabzyRef.value[index]) return;
// 获取当前行的 DOM 元素
const rowElement = (tabzyRef.value[index] as any).$el.querySelector(`.el-table__row.current-row`);
if (rowElement) {
  // 使用 scrollIntoView 将当前行滚动到可见区域
  rowElement.scrollIntoView({ block: 'center' });
}
}

defineExpose({
    emptyDrugList,
    setDrugClassArray,
    handleAddDrug,
    itemValidate,
    applyRowClick,
    saveIsOk,
    templateQuote
})
</script>

<style scoped>
.west-style {
    margin: 10px 10px 10px 7px;
    padding: 0;
    background-color: #c6f4ce;
}

:deep(.el-input-group__append) {
    padding: 0 5px;
    width: 70px;
}

.top-row {
    background-color: #68e3fd;
    margin-left: 1px !important;
    height: 27px;
    position: absolute;
    z-index: 1;
    width: 100%;
}

:deep(.el-popper.is-dark) {
    margin-top: 19px;
}

:deep(.el-popper[data-popper-placement^=right]>.el-popper__arrow) {
    margin-top: -18px;
}
</style>
